package com.carassistant.beta.phone.adapter;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.carassistant.beta.R;
import com.carassistant.beta.common.BitmapCache;
import com.carassistant.beta.common.CarAssistantApp;
import com.carassistant.beta.phone.PhoneContactActivity;

public class ContactAdapter extends BaseAdapter { 
	private LayoutInflater inflater;
	private ArrayList<ContentValues> list; 
	private Activity context;
	private LinearLayout.LayoutParams params;
	private int height; 
	public ContactAdapter(Activity context, ArrayList<ContentValues> list) {
		this.inflater = LayoutInflater.from(context);
		this.list = list;  
		this.context = context;
		height = CarAssistantApp.screenMin/5; 
		params = new LinearLayout.LayoutParams(height, height);
		params.setMargins(5, 10, 5, 10);
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
  
	public void notifyData(ArrayList<ContentValues> list){
		this.list = list;
		notifyDataSetChanged();
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) { 
		ViewHolder holder;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.phone_contact_list_item, null);
			holder = new ViewHolder();
			holder.image = (ImageView) convertView
					.findViewById(R.id.image_view);
			holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.number = (TextView) convertView.findViewById(R.id.number);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		ContentValues cv = list.get(position);
		 
		String number = cv.getAsString(PhoneContactActivity.NUMBER);
		String[] numbers = number.split("\n");
		if(numbers.length>1){
			holder.number.setText("");
		}else{
			holder.number.setText(numbers[0]);
		}
		
		String currentStr = getAlpha(list.get(position).getAsString(PhoneContactActivity.SORT_KEY));
		String previewStr = (position - 1) >= 0 ? getAlpha(list.get(
				position - 1).getAsString(PhoneContactActivity.SORT_KEY)) : "";
		if (!previewStr.equals(currentStr)) {
			holder.alpha.setVisibility(View.VISIBLE);
			holder.alpha.setText(currentStr);
		} else {
			holder.alpha.setVisibility(View.GONE);
		}
 
		String name = cv.getAsString(PhoneContactActivity.NAME);
		
		holder.image.setLayoutParams(params);
		holder.image.setScaleType(ScaleType.FIT_XY);
		
		Bitmap icon = getContactIcon(cv.getAsInteger(PhoneContactActivity.ID));
		if (icon != null) {
			holder.image.setImageBitmap(icon); 
		} else{
			holder.image.setImageBitmap(BitmapCache.getInstance().getBitmap2(context.getResources(), R.drawable.default_contact_icon));
		}
		holder.name.setText(name); 
		
		if(icon!=null && icon.isRecycled()){
			icon.recycle();
		}
		
		return convertView;
	}

	private class ViewHolder {
		ImageView image;
		TextView alpha;
		TextView name;
		TextView number;
	}

	//获得汉语拼音首字母
    private String getAlpha(String str) {  
        if (str == null || str.trim().length() == 0) {  
            return "#";  
        }   
  
        char c = str.trim().substring(0, 1).charAt(0);   
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");  
        if (pattern.matcher(c + "").matches()) {  
            return (c + "").toUpperCase();  
        } else {  
            return "#";  
        }  
    } 
    
    /**
	 * 根据ContactId获取联系人头像
	 * @param id
	 * @return Bitmap
	 * */
    private Bitmap getContactIcon(int contactID){
    	if (contactID != -1) {
    		Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactID);
    		InputStream input = ContactsContract.Contacts
    				.openContactPhotoInputStream(context.getContentResolver(), uri);
    		if (null != input) {
    			return BitmapFactory.decodeStream(input);
    		}
		} 
		return null;
    }
}
